"""
Author        yongfa
Date          2023-08-31 03:37:55
LastEditTime  2023-09-08 07:22:50
LastEditors   yongfa
Description   业务处理
"""
from flask import current_app

from app.extensions.services import BaseService
from app.extensions.sqlalchemy import pagination_to_dict
from app.extensions.exception import Success, Failed, APIException
from app.extensions.utils.validator import validate_columns
from app.app_celery.parserMail.emailLogin import EmailLogin
from app.app_celery.parserMail.tasks import HandleEmailTasks
from app.app_celery.parserJobs.tasks import HandleResumeParser

from .models import EmailInfo


class EmailInfoService(BaseService):
    pass


class ResumeEmailTaskService(BaseService):

    def get_list(self):
        """分页列表"""
        page = self.args.get('page', 1)
        size = self.args.get('size', 20)
        queryset = self.get_all_query()
        paginator = queryset.paginate(page=page, per_page=size, error_out=True)
        data = pagination_to_dict(paginator)
        # for item in data.get('items'):
        #     item['celery_task_state'] = HandleEmailTasks.AsyncResult(
        #         item['celery_task_id']).state if item.get('celery_task_id') else ''
        return Success(data)

    def check_email_login(self):

        email_host = self.args.get('email_host')
        email = self.args.get('email')
        email_password = self.args.get('email_password')
        email_protocol = self.args.get('email_protocol')
        email_port = self.args.get('email_port')
        email_ssl = self.args.get('email_ssl')

        status = EmailLogin(email_host, email_port, email, email_password, email_protocol, email_ssl).check_login()
        if not status:
            return Failed(msg='邮箱登录失败')
        return Success(message='邮箱登录成功')

    def test_pull_email(self):
        email_host = self.args.get('email_host')
        email = self.args.get('email')
        email_password = self.args.get('email_password')
        email_protocol = self.args.get('email_protocol')
        email_port = self.args.get('email_port')
        email_ssl = self.args.get('email_ssl')

        result = EmailLogin(email_host, email_port, email, email_password, email_protocol, email_ssl).get_mails()
        if isinstance(result, APIException):
            return result
        return Success(result=result)

    def create(self):
        """创建"""

        _email_info = validate_columns(EmailInfo, self.args)
        if _email_info:
            email_password = self.args.pop('email_password')
            email = _email_info.get('email')
            email_info = EmailInfo.get(email=email)
            if email_info is None:
                email_info = EmailInfo.create(**_email_info, commit=False)
                email_info.email_password = email_password
                email_info.flush()
            else:
                email_info.update(**_email_info, commit=False)
                email_info.email_password = email_password
        if current_app.config.get('RESUME_EMAIL_TASK_LIMIT'):
            limit_mins = current_app.config.get('RESUME_EMAIL_TASK_LIMIT_MINS')
            recent_task = self.model.get_recent_task(company_email_id=email_info.id, minites=limit_mins)
            if recent_task:
                return Failed(message='最近3分钟内创建过任务,请稍后再创建！')

        data = validate_columns(self.model, self.args)
        if email_info:
            data.update({'company_email_id': email_info.id})
        if self.conditions:
            data.update(self.conditions)

        email_task = self.model.create(**data)

        if current_app.config.get('CELERY_DEBUG_MODEL'):
            HandleEmailTasks(email_task_id=email_task.id)
        else:
            celery_task_id = HandleEmailTasks.apply_async(args=(email_task.id,))
            email_task.update(celery_task_id=celery_task_id)

        return Success()

    def get_detail(self, id):
        """详情"""
        conditions = {'id': id}
        if self.conditions:
            conditions.update(self.conditions)
        item = self.model.get_or_404(**conditions)
        result = item.to_dict()
        if item.celery_task_id:
            _task = HandleEmailTasks.AsyncResult(item.celery_task_id).date_done
            result['celery_task_date_done'] = _task.strftime('%Y-%m-%d %H:%M:%S') if _task else None
            result['celery_task_state'] = HandleEmailTasks.AsyncResult(item.celery_task_id).state
        return Success(result=result)


class ResumeEmailService(BaseService):
    pass


class ResumeParserTaskService(BaseService):

    def create(self):
        """创建"""
        data = validate_columns(self.model, self.args)
        if self.conditions:
            data.update(self.conditions)
        item = self.model.create(**data)
        if not item.callback_url:
            _email_content = HandleResumeParser(resume_parser_task_id=item.id)
            return Success(_email_content)
        if current_app.config.get('CELERY_DEBUG_MODEL'):
            HandleResumeParser(resume_parser_task_id=item.id)
        else:
            celery_task_id = HandleResumeParser.apply_async(args=(item.id,))
            item.update(celery_task_id=celery_task_id.id)
        return Success()


class ResumeContentService(BaseService):
    pass
